# coding: utf-8

import json

import jpush
from jpush import Device
from jpush import common as jpush_common

from common.bid_notify.constant import JPUSH_APP_KEY, JPUSH_APP_SECRET, \
    JPUSH_ALIAS_PREFIX
from common.constant import REGISTRATION_USER_HASH
from common.log import Log
from common.utils import redis_client


def get_demand_info(demand):
    malf_display = {
        0: '其它',
        1: '整屏或部分不亮',
        2: '出现亮点暗点',
        3: '有色彩问题',
        4: '无法更换屏幕内容',
        5: '屏幕移位',
    }

    demand_info = ''
    # 面积
    if demand.cate == 1 and demand.size > 0:
        demand_info += '，约{size}㎡'.format(
            size=round(demand.size, 1))

    # 使用场地
    if demand.surr:
        demand_info += '，{surr_display}'.format(
            surr_display=str(demand.surr_display))
    else:
        demand_info += '，户外'

    # 颜色
    if demand.color:
        demand_info += '{color_display}'.format(
            color_display=demand.color_display)
    else:
        demand_info += '全彩'

    # 间距
    if demand.span:
        demand_info += '，{span}'.format(span=demand.span)

    # 故障描述
    if demand.cate == 2:
        if demand.malf:
            demand_info += '，{malf_display}'.format(
                malf_display=malf_display[demand.malf])
        else:
            demand_info += '，其他故障'

    # 预算
    if demand.budget < 100:
        demand_info += '，预算暂无'
    elif demand.budget < 1000:
        budget = round(demand.budget / 100, 1)
        tmp_split_budget = str(budget).split('.')
        print('*' * 50)
        print(tmp_split_budget)
        print('*' * 50)
        if tmp_split_budget[-1] == '0':
            budget = int(budget)
        demand_info += '，预算{budget}百'.format(budget=budget)
    elif demand.budget < 10000:
        budget = round(demand.budget / 1000, 1)
        tmp_split_budget = str(budget).split('.')
        if tmp_split_budget[-1] == '0':
            budget = int(budget)
        demand_info += '，预算{budget}千'.format(budget=budget)
    else:
        budget = round(demand.budget / 10000, 1)
        tmp_split_budget = str(budget).split('.')
        if tmp_split_budget[-1] == '0':
            budget = int(budget)
        demand_info += '，预算{budget}万'.format(budget=budget)
    return demand_info


def exception_handler(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            Log.info('function:{} params:{}{}'.format(
                func.__name__, args, kwargs)
            )
            Log.info('Push Error {}'.format(repr(e)))

    return wrapper


class JPushType(object):

    NOTIFICATION = 1    # 通知
    MESSAGE = 2         # 自定义消息


class JPush(object):
    """
    create by ld_wu 2018-05-14
    极光推送
    """

    class _Device(Device):
        """
        create by ld_wu 2018-06-25
        """

        def get_device_status(self, registration_ids):
            """
            create by ld_wu 2018-06-25
            获取
            """
            url = '{}/status'.format(jpush_common.get_url('device'))
            body = json.dumps(dict(registration_ids=registration_ids))
            info = self.send('POST', url, body)
            return info

    def __init__(self):
        self._jpush = jpush.JPush(JPUSH_APP_KEY, JPUSH_APP_SECRET)

    @exception_handler
    def send_by_alias(
            self, content, alias_list,
            title=None, ext=None,
            push_type=JPushType.MESSAGE, max_length=999):
        """
        通过别名进行极光推送
        暂时支持推送安卓
        :return:
        """
        if not alias_list:
            return
        prefix = JPUSH_ALIAS_PREFIX
        if prefix:
            alias_list = ['{}_{}'.format(prefix, alias) for alias in alias_list]

        for i in range(0, len(alias_list), max_length):
            send_alias = alias_list[i: i + max_length]
            push = self._jpush.create_push()
            # 发送对象
            push.audience = jpush.audience(jpush.alias(*send_alias))
            if push_type == JPushType.MESSAGE:
                # 发送内容
                push.message = jpush.message(
                    content,
                    title=title,
                    extras=ext
                )
            elif push_type == JPushType.NOTIFICATION:
                push.notification = jpush.notification(
                    android=jpush.android(
                        alert=content,
                        title=title
                    )
                )
            # 发送平台
            push.platform = ['android']
            res = push.send()
            return res

    @exception_handler
    def get_register_id_by_alias(self, alias):
        device = self._jpush.create_device()
        platform = 'android,ios'
        return device.get_aliasuser(alias, platform)

    @exception_handler
    def devices_status(self, registration_ids):
        """
        create by ld_wu 2018-06-25
        获取用户在线状态
        :param registration_ids:
        :return:
        """
        if registration_ids:
            device = self._Device(self._jpush)
            res = device.get_device_status(registration_ids)
            if res:
                return res.payload
        return dict()

    @exception_handler
    def smart_send_by_alias(
            self,
            content,
            alias_list,
            title=None,
            ext=None,
            notify_tile=None,
            notify_content=None):
        """
        create by ld_wu 2018-06-25
        在线直接推送自定义消息
        不在线推送系统通知及自定义消息
        :return:
        """
        registration = redis_client.hgetall(REGISTRATION_USER_HASH) or dict()
        user_id_mapping = {
            reg_id.decode('utf-8'): user_id.decode('utf-8')
            for reg_id, user_id in registration.items()
        }

        registration_ids = [
            reg_id
            for reg_id, user_id in user_id_mapping.items()
            if int(user_id) in alias_list
        ]

        device_status = self.devices_status(registration_ids)
        notify_alias = [
            user_id_mapping.get(register_id)
            for register_id, data in device_status.items()
            if not data.get('online')
        ]

        if notify_alias:
            Log.info(notify_alias)
            # 发送通知
            self.send_by_alias(
                notify_content,
                notify_alias,
                notify_tile,
                ext,
                JPushType.NOTIFICATION
            )
        Log.info(alias_list)
        # 发送自定义消息
        self.send_by_alias(content, alias_list, title, ext)


if __name__ == '__main__':

    message = dict(
        msg='{cate}订单，位置：{address} {demand_info}'.format(
            cate='安装',
            address='深圳',
            demand_info='订单详情'
        ),
        type=0,
        ext=json.dumps(
            dict(demand_id=1000)
        )
    )
    app_msg_content = dict(
        data=message,
        msg_type=10
    )
    print(
        JPush().send_by_alias(
            '深圳市、20m、室内、P3',
            [1007051],
            '安装订单',
            dict(demand_id=1000, demand_status=9)
        )
    )
